<?php
require_once 'pages/TMSItemPage.inc';

class TMSItemCreationPage extends TMSItemPage {
	
	protected $creationClass = null;
	
	protected function getItem(){		
		return new TMSPageItem($this->Model->GetDummyItem(null,$this->creationClass),$this);
	}
	
	public function Handle(THttpRequest $request){
		if (count($this->Model->ExplicitDescendants) == 0)
			$this->creationClass = $this->Model->ClassName();
		else if ($request->itemtype)
			$this->creationClass = $request->itemtype;
		
		return parent::Handle($request);
	}
	
	public function http_SelectCreationType($type){
		$this->creationClass = $type;
	}
	
	protected function processUrlParameters(array $parameters){
			$parameters['itemtype'] = $this->creationClass;
		return parent::processUrlParameters($parameters);
	}	
	
	public function NeedSelectClass(){
		return is_null($this->creationClass);
	}
	
	public function ClassSelection(){
		$c = false;
		if ($this->Service()->MetaSettings)
			$c = $this->Service()->MetaSettings->GetValue($this->Model->ClassName().'.Caption');
		
		$result = array($this->Model->ClassName()=>$c?$c:$this->Model->ClassName());
		foreach ($this->Model->ExplicitDescendants as $class){
			$c = false;
			if ($this->Service()->MetaSettings)
				$c = $this->Service()->MetaSettings->GetValue($class.'.Caption');
			if ($c)
				$result[$class] = $c;
			else
				$result[$class] = $class;
		}
		return $result;
	}
	
	protected function doCreate($data){
		return $this->Model->CreateItem($data, $this->creationClass);
	}
	
	protected function doSave($data){
		$item = $this->doCreate($data);
		if ($item)
			$this->Application()->Redirect($this->service->ItemEditUrl($item));
	}
}